from rest_framework.decorators import action
from rest_framework.mixins import *
from rest_framework.request import HttpRequest
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import *
from django.db import transaction
from apps.tcpserver import request_type
from apps.user.models import User
from .filters import *
from .serializers import *
from apps.log.models import UserActionLog


class DevicesView(ReadOnlyModelViewSet, UpdateModelMixin):
    filter_class = DevicesFilter
    queryset = Devices.objects.all()
    serializer_class = DevicesModelSerializer

    def filter_queryset(self, queryset):

        user: User = self.request.user
        if user.is_superuser:
            queryset = super().filter_queryset(queryset)

        else:
            queryset = super().filter_queryset(user.devices_set)
        region = self.request.query_params.get('region')
        if region and region != '0':
            return queryset.filter(region__id__in=[int(region)])
        return queryset.all()

    @action(methods=['put'], detail=True, url_path='permission')
    def change_user(self, request, *args, **kwargs):
        users_id = request.data.get('users', [])
        devices: Devices = self.get_object()

        if request.user.is_superuser:
            user = User.objects.all()
            devices.user.remove(*user)
        else:
            user = User.objects.filter(parent_user__id=request.user.id).all()
            devices.user.remove(*user)

        users = user.filter(id__in=users_id)
        devices.user.add(*users)

        return Response({
            'code': 200,
            'msg': '修改成功'
        })


class DevicesControllersView(GenericViewSet, ListModelMixin):
    filter_class = ControlsFilter
    queryset = Controls.objects.all()
    serializer_class = ControlSerialzer
    pagination_class = None

    def filter_queryset(self, queryset):

        result = super().filter_queryset(queryset)
        dev = Devices.objects.filter(
            id=self.request.query_params['devices']
        ).first()
        group = dev.controlgroup_set.values('sub_device_1', 'sub_device_2')
        for i in group:
            result = result.exclude(number__in=i.values())
        return result

    def get_serializer_context(self, **kwargs):
        context = super().get_serializer_context(**kwargs)
        dev = Devices.objects.filter(
            id=self.request.query_params['devices']
        ).first()
        context['dev'] = dev
        hanle_type = btoi(request_type.PAYLOAD_REQ_TO_MCU_GET_INPUT)
        res = TCPManager.get_instance().offer(
            dev.device_serial_number,
            {
                'output_type': 0,
                'output_channle': 0
            },
            handle_type=hanle_type,
            time_out=settings.TASK_TIME_OUT
        )
        if res:
            controls_status = {
                str(i['output_channle']): i
                for i in res['msg']['controlls']
            }
            context["controls_status"] = controls_status
        return context

    @action(methods=["put"], detail=True, url_path="rule")
    def update_auto_rule(self, request, *args, **kwargs):
        control: Controls = self.get_object()
        if request.data['mode'] == Controls.MODE_MANUAL:
            control.mode = Controls.MODE_MANUAL
            auto_rule = AutoRule.objects.filter(
                output_channle=control.number, output_type=0, devices_id=control.devices.id)
            UserActionLog.objects.create(
                user=request.user,
                devices=control.devices,
                description=f"修改继电器{control.alias}状态为手动控制"
            )
            for i in auto_rule:
                serial = AutoRuleSerializer(
                    instance=i, context=self.get_serializer_context())
                data = serial.data
                data['rule_code'] = 0
                # data['devices'] = 0
                serial.update(i, data)

        else:
            with transaction.atomic() as tr:
                control.mode = request.data['mode']
                rules = request.data['rules']
                ids = [i.get('id') for i in rules if i.get('id')]
                time_status = request.query_params.get('time_status', '1')
                closed = AutoRule.objects.filter(
                    output_type=0,
                    output_channle=control.number,
                    rule_code=1,
                    devices_id=control.devices.id,

                ).exclude(
                    time_status=int(time_status),
                ).all()
                for i in closed:
                    data = AutoRuleSerializer(
                        instance=i,
                        context={'request': request, 'dev': control.devices}
                    ).data
                    # 修改status 标记设备ROM段中该串空间可用  并关闭自动规则
                    data['rule_code'] = 0
                    # 发布事件
                    resp = TCPManager.get_instance().offer(
                        control.devices.device_serial_number,
                        {
                            'item': 'auto_rule',
                            'subitem': 'settings',
                            'data': [data],
                            'index': int(i.rule_number) - 1
                        },
                        handle_type=3,
                        is_callback=True
                    )
                    i.rule_code = 0
                    i.save()

                delete = AutoRule.objects.filter(
                    time_status=0 if request.data['mode'] == Controls.MODE_AUTO else 1, 
                    output_type=0, 
                    output_channle=control.number, 
                    devices_id=control.devices.id
                    ).exclude(id__in=ids)
                for i in delete:
                    data = AutoRuleSerializer(
                        instance=i,
                        context={'request': request, 'dev': control.devices}
                    ).data
                    # 修改status 标记设备ROM段中该串空间可用  并关闭自动规则
                    data['status'] = 0
                    data['rule_code'] = 0
                    data['rule_number'] = 0
                    # 发布事件
                    resp = TCPManager.get_instance().offer(
                        control.devices.device_serial_number,
                        {
                            'item': 'auto_rule',
                            'subitem': 'settings',
                            'data': [data],
                            'index': int(i.rule_number) - 1
                        },
                        handle_type=3,
                        is_callback=False
                    )
                    i.delete()
                for i in rules:
                    if i.get('id'):
                        rule_instance = AutoRule.objects.filter(
                            id=i['id']).first()
                        serial = AutoRuleSerializer(
                            data=i, context={'request': request, 'dev': control.devices})
                        serial.is_valid(raise_exception=True)
                        data = serial.validated_data
                        data['rule_code'] = 1
                        serial.update(rule_instance, data)
                    else:
                        serial = AutoRuleSerializer(
                            data=i,
                             context={'request': request, 'dev': control.devices}
                             )
                        serial.is_valid(raise_exception=True)
                        serial.create(serial.validated_data)

                UserActionLog.objects.create(
                    user=request.user,
                    devices=control.devices,
                    description=f"修改{control.alias}下得 {'自动规则' if time_status == '0' else'定时规则'}"
                )
        control.save()
        return Response({"code": 200, 'msg': '修改成功'})


class ControlActionView(APIView):

    def post(self, request, *args, **kwargs):
        types = request.data.get('output_type', 0)
        if types == 0:

            obj = Controls.objects.filter(id=kwargs['id']).first()
        elif types == 3:
            obj = ControlGroup.objects.filter(id=kwargs['id']).first()
        device_serial_number = obj.devices.device_serial_number
        data = request.data.get('data', 1)
        output_type = request.data.get('output_type', 0)
        hanle_type = btoi(request_type.PAYLOAD_REQ_TO_MCU_SET_OUTPUT)
        res = TCPManager.get_instance().offer(device_serial_number, {
            'number': obj.number,
            "data": data,
            'output_type': output_type
        }, hanle_type, time_out=settings.TASK_TIME_OUT)

        if res:
            UserActionLog.objects.create(
                user=request.user,
                devices=obj.devices,
                description=f"修改继电器{obj.alias}状态为 {data}"
            )
            return Response({
                'code': 200,
                "data": res['msg']
            })
        else:
            return Response({
                'code': 400,
                'msg': '失败'
            }, status=400)

    def patch(self, request, *args, **kwargs):
        obj = Controls.objects.filter(id=kwargs['id']).first()
        serializer = ControlSerialzer(obj, data=request.data)
        UserActionLog.objects.create(
            user=request.user,
            devices=obj.devices,
            description=f"修改继电器配置"
        )
        if serializer.is_valid():
            if request.data.get('mode') == 0:
                closed = AutoRule.objects.filter(
                    output_type=0,
                    output_channle=obj.number,
                    rule_code=1,
                    devices_id=obj.devices.id
                ).all()
            elif request.data.get('mode') == 1:
                closed = AutoRule.objects.filter(
                    output_type=0,
                    output_channle=obj.number,
                    rule_code=1,
                    devices_id=obj.devices.id
                ).exclude(
                    time_status=1
                ).all()

            else:
                closed = AutoRule.objects.filter(
                    output_type=0,
                    output_channle=obj.number,
                    rule_code=1,
                    devices_id=obj.devices.id
                ).exclude(
                    time_status=2
                ).all()

            for i in closed:
                data = AutoRuleSerializer(
                    instance=i,
                    context={'request': request, 'dev': obj.devices}
                ).data
                # 修改status 标记设备ROM段中该串空间可用  并关闭自动规则
                data['rule_code'] = 0
                # 发布事件
                resp = TCPManager.get_instance().offer(
                    obj.devices.device_serial_number,
                    {
                        'item': 'auto_rule',
                        'subitem': 'settings',
                        'data': [data],
                        'index': int(i.rule_number) - 1
                    },
                    handle_type=3,
                    is_callback=True
                )
                i.rule_code = 0
                i.save()

            serializer.save()
            return Response({
                'code': 200,
                'msg': '修改成功'
            })

        return Response({
            'code': 400,
            'msg': serializer.errors
        }, status=400)

    def put(self, request, *args, **kwargs):
        return self.patch(request, *args, **kwargs)


class SensorView(ModelViewSet):
    """
    采集器
    """
    queryset = Sensor.objects.order_by('id').all()
    filter_class = SensorFilter
    serializer_class = SensorSerialzer
    pagination_class = None

    def filter_queryset(self, queryset):
        queryset = super().filter_queryset(queryset)
        return queryset

    def get_serializer_context(self):
        context = super(SensorView, self).get_serializer_context()
        dev = Devices.objects.filter(
            id=self.request.query_params['devices']).first()
        context['dev'] = dev
        return context

    def update(self, request, *args, **kwargs):
        # sensors = self.get_queryset().orderby
        try:
            res = super().update(request, *args, **kwargs)
            sensor: Sensor = self.get_object()
            UserActionLog.objects.create(
                user=request.user,
                devices=sensor.devices,
                description=f"修改485传感器{sensor.name}配置"
            )

            return res
        except Exception as e:
            return Response({
                'code': 400,
                'msg': '修改失败'
            })

    def destroy(self, request, *args, **kwargs):
        instance: Sensor = self.get_object()
        context = self.get_serializer_context()
        data = self.get_serializer_class()(instance=instance, context=context).data

        data['start'] = 0
        data['input_number'] = 0
        data['name'] = ''
        res = TCPManager.get_instance().offer(
            instance.devices.device_serial_number, msg={
                'item': 'sensor_485',
                'subitem': 'settings',
                'data': [data],
                'index': instance.input_number - 1
            }, handle_type=3, time_out=settings.TASK_TIME_OUT)
        if res:
            UserActionLog.objects.create(
                user=request.user,
                devices=instance.devices,
                description=f"删除485传感器{instance.name}配置"
            )
            return super(SensorView, self).destroy(request, *args, **kwargs)
        return Response({
            'code': 200,
            'msg': '设备无响应，请检查设备是否设置成功'
        })


class DevicesConfigView(GenericViewSet, RetrieveModelMixin, UpdateModelMixin):
    queryset = Devices.objects.all()
    serializer_class = DevicesModelSerializer

    def retrieve(self, request: HttpRequest, *args, **kwargs):
        dev: Devices = self.get_object()
        manage = TCPManager.get_instance()
        manage_type = btoi(request_type.PAYLOAD_REQ_READ_ALL_CONFIG)

        res = manage.offer(
            dev.device_serial_number,
            request.query_params,
            1001,
            manage_type,
            time_out=settings.TASK_TIME_OUT
        )
        if isinstance(res, dict):

            return Response({
                'code': 200,
                'data': res['msg']
            })
        else:
            return Response({
                'code': 502,
                'msg': '请求超时'
            }, status=500)

    def update(self, request, *args, **kwargs):
        items = request.data.get('items', [])
        dev: Devices = self.get_object()
        for i in items:
            manage = TCPManager.get_instance()
            manage_type = btoi(request_type.PAYLOAD_REQ_READ_ALL_CONFIG)
            reboot_type = btoi(request_type.PAYLOAD_REQ_REBOOT)
            res = manage.offer(
                dev.device_serial_number,
                i,
                3,
                time_out=settings.TASK_TIME_OUT
            )
        UserActionLog.objects.create(
            user=request.user,
            devices=dev,
            description=f"修改了{dev.alias}设备下得系统配置"
        )
        return Response({
            'code': 200,
            'msg': '修改成功'
        })


class ReBootView(APIView):

    def post(self, request, *args, **kwargs):
        dev_id = kwargs['pk']
        devices = Devices.objects.filter(id=dev_id).first()
        if devices:
            devices.status = False
            manage = TCPManager.get_instance()
            manage_type = btoi(request_type.PAYLOAD_REQ_REBOOT)
            res = manage.offer(
                devices.device_serial_number,
                {},
                manage_type
            )

            UserActionLog.objects.create(
                user=request.user,
                devices=devices,
                description=f"重启设备{devices.alias}"
            )

        return Response({
            'code': 200,
            'msg': '成功'
        })


class AutoUploadDataView(APIView):

    def post(self, request, *args, **kwargs):
        dev_id = kwargs['pk']
        status = request.data.get('status')
        devices = Devices.objects.filter(id=dev_id).first()
        if devices:
            manage = TCPManager.get_instance()
            manage_type = btoi(
                request_type.PAYLOAD_REQ_TO_MCU_ENABLE_UP_REPORT
            )
            res = manage.offer(
                devices.device_serial_number,
                {
                    'status': status
                },
                manage_type
            )

        return Response({
            'code': 200,
            'msg': '成功'
        })


class HistoryView(ReadOnlyModelViewSet):
    queryset = History.objects.order_by('id').all()
    serializer_class = HistorySerialzer
    filter_class = SensorHistoryFilter

    def filter_queryset(self, queryset):
        queryset = super().filter_queryset(queryset)

        if self.request.user.is_superuser:
            return queryset
        else:
            devices = self.requets.user.devices_set.all()
            queryset.filter(devices__in=devices).all()
            return queryset

    def paginate_queryset(self, queryset):
        return super().paginate_queryset(queryset)


class AutoRuleView(ModelViewSet):
    filter_class = AutoRuleFilter
    serializer_class = AutoRuleSerializer
    queryset = AutoRule.objects.all()
    pagination_class = None

    def filter_queryset(self, request, *args, **kwargs):
        query_set = super().filter_queryset(
            request,
            *args,
            **kwargs
        )
        return query_set

    def get_serializer_context(self):
        context = super().get_serializer_context()

        dev = Devices.objects.filter(
            id=self.request.query_params['devices']
        ).first()
        context['dev'] = dev

        return context

    def destroy(self, request, *args, **kwargs):
        """
            删除一个自动规则
        """
        instance: AutoRule = self.get_object()
        dev: Devices = instance.devices
        serializer: type = self.get_serializer_class()
        # 获取自动规则数据
        data = serializer(
            instance=instance
        ).data
        # 修改status 标记设备ROM段中该串空间可用  并关闭自动规则
        data['status'] = 0
        data['rule_code'] = 0
        data['rule_number'] = 0
        # 发布事件
        resp = TCPManager.get_instance().offer(
            dev.device_serial_number,
            {
                'item': 'auto_rule',
                'subitem': 'settings',
                'data': [data],
                'index': int(instance.rule_number) - 1
            },
            handle_type=3,
            time_out=settings.TASK_TIME_OUT
        )
        if not resp:
            return Response(
                {
                    'code': 408,
                    'msg': '设备响应超时，请检查设备是否设置完成'
                },
                status.HTTP_408_REQUEST_TIMEOUT
            )
        UserActionLog.objects.create(
            user=request.user,
            devices=instance.devices,
            description=f"删除了自动规则{instance.name}"
        )
        return super(AutoRuleView, self).destroy(request, *args, **kwargs)


class ControlGroupView(ModelViewSet):
    pagination_class = None
    queryset = ControlGroup.objects.all()
    serializer_class = ControlGroupSerializer
    filter_class = ControlGroupFilter

    def get_serializer_context(self, **kwargs):
        context = super().get_serializer_context(**kwargs)
        dev = Devices.objects.filter(
            id=self.request.query_params['devices']
        ).first()
        hanle_type = btoi(request_type.PAYLOAD_REQ_TO_MCU_GET_INPUT)
        res = TCPManager.get_instance().offer(
            dev.device_serial_number,
            {
                'output_type': 3,
                'output_channle': 0
            },
            handle_type=hanle_type,
            time_out=settings.TASK_TIME_OUT
        )
        if res:
            controls_status = {i['output_channle']                               : i for i in res['msg']['controlls']}
            context["controls_status"] = controls_status
            context["dev"] = dev
        return context

    def destroy(self, request, *args, **kwargs):
        instance: ControlGroup = self.get_object()
        data = ControlGroupSerializer(instance=instance).data
        data['is_use'] = 0
        data['start'] = 0
        res = TCPManager.get_instance().offer(
            instance.devices.device_serial_number,
            msg={
                'item': 'number_group_output',
                'subitem': 'settings',
                'data': [data],
                'index': instance.number - 1
            },
            handle_type=3,
            time_out=settings.TASK_TIME_OUT
        )
        if res:
            UserActionLog.objects.create(
                user=request.user,
                devices=instance.devices,
                description=f"删除了组合控制{instance.alias}"
            )
            return super(ControlGroupView, self).destroy(request, *args, **kwargs)

        return Response({
            'code': 200,
            'msg': '设备无响应，请检查设备设置是否完成'
        })

    @action(methods=['put'], detail=True, url_path='rule')
    def add_rule(self, request, *args, **kwargs):
        control: ControlGroup = self.get_object()
        if request.data['mode'] == Controls.MODE_MANUAL:
            control.mode = Controls.MODE_MANUAL
            auto_rule = AutoRule.objects.filter(
                output_channle=control.number, output_type=3, devices_id=control.devices.id)
            for i in auto_rule:
                serial = AutoRuleSerializer(instance=i)

                data = serial.data
                data['rule_code'] = 0
                # data['devices'] = 0
                serial.update(i, data)

            UserActionLog.objects.create(
                user=request.user,
                devices=control.devices,
                description=f"修改{control.alias}组合控制模式为手动"
            )

        else:
            with transaction.atomic() as tr:
                control.mode = request.data['mode']
                time_status = request.query_params.get('time_status', '1')
                rules = request.data['rules']
                ids = [i.get('id') for i in rules if i.get('id')]
                delete = AutoRule.objects.filter(
                    time_status=0 if request.data['mode'] == Controls.MODE_AUTO else 1, 
                    output_type=3,
                    output_channle=control.number,
                    devices_id=control.devices.id
                ).exclude(id__in=ids)
                closed = AutoRule.objects.filter(
                    
                    output_type=3,
                    output_channle=control.number,
                    rule_code=1,
                    devices_id=control.devices.id
                ).exclude(
                    time_status=int(time_status),
                ).all()
                for i in closed:
                    data = AutoRuleSerializer(
                        instance=i,
                        context={'request': request, 'dev': control.devices}
                    ).data
                    # 修改status 标记设备ROM段中该串空间可用  并关闭自动规则
                    data['rule_code'] = 0
                    # 发布事件
                    resp = TCPManager.get_instance().offer(
                        control.devices.device_serial_number,
                        {
                            'item': 'auto_rule',
                            'subitem': 'settings',
                            'data': [data],
                            'index': int(i.rule_number) - 1
                        },
                        handle_type=3,
                        is_callback=True
                    )
                    i.rule_code = 0
                    i.save()

                for i in delete:
                    data = AutoRuleSerializer(
                        instance=i,
                        context={'request': request, 'dev': control.devices}
                    ).data
                    # 修改status 标记设备ROM段中该串空间可用  并关闭自动规则
                    data['status'] = 0
                    data['rule_code'] = 0
                    data['rule_number'] = 0
                    # 发布事件
                    resp = TCPManager.get_instance().offer(
                        control.devices.device_serial_number,
                        {
                            'item': 'auto_rule',
                            'subitem': 'settings',
                            'data': [data],
                            'index': int(i.rule_number) - 1
                        },
                        handle_type=3,
                        is_callback=False
                    )
                    i.delete()

                for i in rules:
                    if i.get('id'):
                        rule_instance = AutoRule.objects.filter(
                            id=i['id']).first()
                        serial = AutoRuleSerializer(
                            data=i, context={'request': request, 'dev': control.devices})
                        serial.is_valid(raise_exception=True)
                        data = serial.validated_data
                        data['rule_code'] = 1
                        serial.update(rule_instance, data,)
                    else:
                        serial = AutoRuleSerializer(
                            data=i, context={'request': request, 'dev': control.devices})
                        serial.is_valid(raise_exception=True)
                        serial.create(serial.validated_data)
                UserActionLog.objects.create(
                    user=request.user,
                    devices=control.devices,
                    description=f"修改{control.alias}下得{'自动规则' if time_status == '1' else '定时规则'}"
                )
        control.save()
        return Response({"code": 200, 'msg': '修改成功'})


class TransmissionView(APIView):

    def post(self, request, *args, **kwargs):
        id = kwargs['pk']
        obj = Devices.objects.filter(id=id).first()
        if obj:
            res = TCPManager.get_instance().offer(
                obj.device_serial_number,
                request.data,
                21
            )
            UserActionLog.objects.create(
                user=request.user,
                devices=obj.devices,
                description=f"向{obj.alias}下下发透传命令  {str(request.data)}"
            )
            return Response({
                'code': 200,
                'msg': '执行成功',
                'data': res
            })

        return Response({
            'code': 404,
            'msg': '找不到设备'
        }, status=400)


class MockControlView(ModelViewSet):
    queryset = MockControls.objects.all()
    filter_class = MockControlGroupFilter
    pagination_class = None
    serializer_class = MockOutputSerializer

    def get_serializer_context(self, **kwargs):
        context = super().get_serializer_context(**kwargs)
        dev = Devices.objects.filter(
            id=self.request.query_params['devices']
        ).first()
        hanle_type = btoi(request_type.PAYLOAD_REQ_TO_MCU_GET_INPUT)
        res = TCPManager.get_instance().offer(
            dev.device_serial_number,
            {
                'output_type': 1,
                'output_channle': 0
            },
            handle_type=hanle_type,
            time_out=settings.TASK_TIME_OUT
        )
        if res:
            controls_status = {str(i['output_channle'])                               : i for i in res['msg']['controlls']}
            context["controls_status"] = controls_status
        return context


class DistributionDevicesView(APIView):
    def post(self, request, *args, **kwargs):
        devices = Devices.objects.filter(id=kwargs['id'])
        # users =


class MockSensorView(ModelViewSet):
    queryset = MockSensor.objects.all()
    serializer_class = MockSensorSerializer
    pagination_class = None

    def get_serializer_context(self):
        context = super().get_serializer_context()
        dev = Devices.objects.filter(
            id=self.request.query_params['devices']).first()

        context['dev'] = dev
        return context

    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        dev = Devices.objects.filter(
            id=request.query_params['devices']
        ).first()
        validate_data = MockSensorSerializer(instance=instance).data
        validate_data['is_use'] = 0
        validate_data['start'] = 0
        res = TCPManager.get_instance().offer(
            dev.device_serial_number,
            msg={
                'item': 'mock_input',
                'subitem': 'settings',
                'data': [validate_data],
                'index': instance.number - 1
            },
            handle_type=3,
            time_out=settings.TASK_TIME_OUT
        )
        if res:
            UserActionLog.objects.create(
                user=request.user,
                devices=dev,
                description=f"删除了模拟量传感器{instance.name}"
            )
            return super().destroy(request, *args, **kwargs)
        raise Exception('destory fail')


class DevicesStatisticsView(APIView):

    def get(self, request, **args):
        user: User = request.user
        if user.is_superuser:
            devices = Devices.objects.all()
            total = devices.count()
            online_devices = len(
                list(
                    filter(lambda x: x.status, devices)
                )
            )
            offline_devices = len(
                list(
                    filter(lambda x: not x.status, devices)
                )
            )
        else:
            devices = user.devices_set.all()
            total = devices.count()
            devices_id = user.devices_set.values('id')
            devices = Devices.objects.filter(
                id__in=devices_id
            ).all()
            online_devices = len(
                list(
                    filter(lambda x: x.status, devices)
                )
            )
            offline_devices = len(
                list(
                    filter(lambda x: not x.status, devices)
                )
            )

        return Response({
            'code': 200,
            'msg': '获取成功',
            'data': {
                'online_devices': online_devices,
                'offline_devices': offline_devices,
                'total': total
            }
        })


class DeviceVideoMonitorView(ModelViewSet):
    queryset = DeviceVideoMonitor.objects.all()
    serializer_class = DeviceVideoMonitorSerializer
    pagination_class = None
    filter_class = DeviceVideoMonitorFilter

    def filter_queryset(self, queryset):
        queryset = super().filter_queryset(queryset)

        user = self.request.user
        if user.is_superuser:
            return queryset
        else:
            devices_ids = user.devices_set.values()
            return queryset.filter(
                devices_id__in=devices_ids
            ).all()


class NumberSensorView(ModelViewSet):
    queryset = NumberSensor.objects.all()
    serializer_class = NumberSensorSerializer
    pagination_class = None
    filter_class = SensorFilter

    def get_serializer_context(self, **kwargs):
        context = super().get_serializer_context(**kwargs)
        dev = Devices.objects.filter(
            id=self.request.query_params['devices']
        ).first()

        if dev:

            context["dev"] = dev
        return context

    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        dev = Devices.objects.filter(
            id=request.query_params['devices']
        ).first()
        validate_data = NumberSensorSerializer(instance=instance).data
        validate_data['is_use'] = 0
        validate_data['start'] = 0
        res = TCPManager.get_instance().offer(
            dev.device_serial_number,
            msg={
                'item': 'number_input',
                'subitem': 'settings',
                'data': [validate_data],
                'index': instance.number - 1
            },
            handle_type=3,
            time_out=settings.TASK_TIME_OUT
        )
        if res:
            UserActionLog.objects.create(
                user=request.user,
                devices=dev,
                description=f"删除了数字量传感器{instance.name}"
            )
            return super().destroy(request, *args, **kwargs)
        raise Exception("destory fail")


class SensorLableValueView(APIView):

    def get(self, request, *args, **kwargs):

        devices = self.request.user.devices_set.all()
